import base64
import requests
from integration.serce.encryption import Images


class Serce_Login:
    def __init__(self,zhi):
        self.__dict__.update(zhi)
        self.session = requests.session()
        self.gety()

    def serce_login_update(self):
        self.url_switch_one_data = {'original_info': '','src_ipv4': '','dst_ipv4': '','log_type': 'sec_event','x_forwarded_for': '','dealStatus': '','event_source': '','attack_type': '','ioc': '',
            'start_time': self.startTime,
            'end_time': self.end_time,
            'start': '0','length': '50'
        }
        response = self.session.post(self.url_switch+'/wlwaq-server//logQuery/initByPage.action', headers=self.headers,
                                 data=self.url_switch_one_data)
        if response.status_code == 200:
            return self
        else:
            self.login()
            self.db_manager.update_cookies(self.url_switch,self.response_cookie['access_token'])
            self.my_logg.info('安全平台获取Auth_Token成功')
        return self


    def login(self,wither=True):
        while wither:
            response = self.session.post(self.url_switch+'/frameapi/frame/authuser/auth/code', headers=self.headers,
                                         verify=False).json()['data']
            self.imgStr = response['code']
            self.key = response['key']
            self.images = Images(self.imgStr, r'log_time_sleeps/logs/img/base64.png')
            try:
                self.code = self.images.base64ToImage()
                wither=False
            except :
                self.my_logg.info('安全平台验证码错误,正常重新识别验证码')
        self.my_logg.info('安全平台验证码通过')
        self.headers['Authorization'] = f"Basic {base64.b64encode('webApp:123456'.encode('utf-8')).decode('utf-8')}"
        self.data_login()
        self.response_cookie = self.session.post(self.url_switch+"/frameapi/oauth/token", headers=self.headers,
                                                 data=self.login_data,
                                                 verify=False).json()
        self.headers['Auth-Token'] = self.response_cookie['access_token']
        return self.response_cookie['access_token']

    def gety(self):
        self.headers = {
            'Accept': 'application/json, text/plain, */*',
            'Accept-Language': 'zh-CN,zh;q=0.9',
            'Connection': 'keep-alive',
            'Content-Length': '0',
            'Auth-Token': self.Auth_Token,
            'User-Agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36',
        }

    # 登录的加密参数
    def data_login(self):
        self.login_data = {
            'grant_type': 'password',
            'username': self.serce_username,
            'password': base64.b64encode(f"{self.serce_username}:{self.serce_password}".encode("utf-8")).decode('utf-8'),
            'code': self.code,
            'key': self.key,
            '': ''
        }
